//将parent环境set到自己的环境中
window.electron = window.top.electron
window.$ = (args) => window.top.$(args, document);
document.notification = window.top.document.notification
document.print = window.top.document.print
document.println = window.top.document.println
document.printclear = window.top.document.printclear
window.GetUUID = window.top.GetUUID
document.Page = window.top.document.Page

const sql = electron.JDBC().sqlite

const clearResult = () => {
    let table = document.querySelector("#search-table");
    let tableBody = table.querySelector("tbody")
    table.removeChild(tableBody);

    table.appendChild(document.createElement("tbody"));
}


//往table插入一行结果
//@param keyword:string 查询关键字
//@param type:number 0|1  0：npk查询 1：img查询
const inertResult = (keyword, type, data) => {
    let npkPath = data.path
    let imgPath = data.img

    if (type == 0) {
        npkPath = npkPath.replaceAll(keyword, `<B>${keyword}</B>`);

    } else {
        imgPath = imgPath.replaceAll(keyword, `<B>${keyword}</B>`);
    }

    let row = $(`<tr class="row" data-id="${data.id}">
        <td><span>${npkPath}</span><button class="exNpk hidden" disabled onclick="exportNpk(this)">导出NPK</button><button class="explorer" onclick="tableExplorer(this)">定位</button></td>
        <td><span>${imgPath}</span><button class="exImg hidden" disabled onclick="exportImg(this)">导出IMG</button><button class="preview" onclick="tableView(this)">预览</button></td>
    </tr>`)

    let tableBody = $(document.querySelector("#search-table tbody"));
    tableBody.append(row);
}

//预览行图片缩放
const previewOnload = (element) => {
    // console.log("图片加载完成!", element.width, element.height);
    let height = element.height;
    let width = element.width;

    if (height >= width) {
        //定高
        element.style.height = "10rem";
    } else {
        //定宽
        element.style.width = "10rem";
        let newHeight = 100 / width * height;
        element.style.margin = (100 - newHeight) / 20 + "rem 0";
    }

    //背景色
    let select = document.querySelector("#bgColorSelect").value;
    switch (select) {
        case "0":
            element.style.background = "inherit"
            break;
        case "1":
            element.style.background = "black"
            break;
        case "2":
            element.style.background = "gray"
            break;
        case "3":
            element.style.background = "white"
            break;
        case "4":
            element.style.background = "red"
            break;
        case "5":
            element.style.background = "blue"
            break;
        case "6":
            element.style.background = "green"
            break;
        case "7":
            element.style.background = "yellow"
            break;
        case "8":
            element.style.background = "purple"
            break;
        case "9":
            element.style.background = "aqua"
            break;
    }

    // console.log(event);
}

const page = new document.Page(); //分页插件

const init = () => {
    // document.println("我是NPK搜索页面")
    document.println("关于NPK搜索器:第一次使用时，请先设置ImagePacks2文件夹路径，然后建立缓存")

    //查询 imagePacks2 路径
    sql.config.queryByName("imagePacks2").then(res => {


        document.querySelector("#ipkPath").value = res.value;
    })

    //挂载分页插件
    page._uuid = "d3003075a91dc4883973476997a2716c4" //固定一个uuid 防止反复加载
    page.mount(document.querySelector("#table-page"), null, "table-page");

    //npk任务回调
    electron.npkReply(replyToken);
}

const searchNpkInit = () => {
    let btn = document.querySelector("#npk-search-btn");
    btn.addEventListener("click", () => {
        let inputVal = document.querySelector("#npkPath").value
        if (!inputVal || inputVal == "") {
            return;
        }

        btn.disabled = true;
        btn.className += " wait"
        clearResult();

        sql.npkIndex.queryCountNpkLike(inputVal)
            .then(data => {
                console.log("data", data);
                if (data && data.num > 0) {
                    page.reset();
                    page.value = inputVal;
                    page.callback = searchNpkQuery;
                    page.setCount(data.num);
                    page.query();
                } else {
                    document.println(`未查询到结果`)
                    btn.disabled = false;
                    btn.className = "";
                }
            })
    })
}

const searchNpkQuery = (page, value, limit, offset) => {
    let btn = document.querySelector("#npk-search-btn");
    sql.npkIndex.queryNpkLike(value, limit, offset)
        .then(res => {
            console.log(res);
            clearResult();
            btn.disabled = false;
            btn.className = "";
            if (res && res.length > 0) {
                res.forEach(rs => {
                    inertResult(value, 0, rs);
                })
            } else {
                document.println(`未查询到结果`)
            }

        }).catch(e => {
            btn.disabled = false;
            btn.className = "";
            document.println(`未查询到结果,${e.toString()}`)
        })
}

const sendChannelBuildCache = () => {
    const ipkPathInput = document.querySelector("#ipkPath")
    const path = ipkPathInput.value;

    if (path == "") {
        document.println("请先选择imagePacks2文件夹");
        return;
    }

    const token = GetUUID()
    electron.npkSend("cache_dirPath", token, path);

    ipkPathInput.disabled = true;


    const cache_btn = document.querySelector("#cache_btn")
    cache_btn.disabled = true;
    cache_btn.className = "wait";

    const choose_btn = document.querySelector("#choose_btn")
    choose_btn.disabled = true;

    const all_btn = document.querySelector("#all_btn")
    all_btn.disabled = true;

    const npkSearchBtn = document.querySelector("#npk-search-btn")
    npkSearchBtn.disabled = true;

    const imgSearchBtn = document.querySelector("#img-search-btn");
    imgSearchBtn.disabled = true;


    clearResult();
}

const searchImgInit = () => {
    let btn = document.querySelector("#img-search-btn");
    btn.addEventListener("click", () => {
        let inputVal = document.querySelector("#imgPath").value
        if (!inputVal || inputVal == "") {
            return;
        }

        btn.disabled = true;
        btn.className += " wait"
        clearResult();

        sql.npkIndex.queryCountImgLike(inputVal)
            .then(data => {
                console.log("data", data);
                if (data && data.num > 0) {
                    page.reset();
                    page.value = inputVal;
                    page.callback = searchImgQuery;
                    page.setCount(data.num);
                    page.query();
                } else {
                    document.println(`未查询到结果`)
                    btn.disabled = false;
                    btn.className = "";
                }
            })
    })

}

const searchImgQuery = (page, value, limit, offset) => {
    let btn = document.querySelector("#img-search-btn");
    sql.npkIndex.queryImgLike(value, limit, offset)
        .then(res => {
            clearResult();
            btn.disabled = false;
            btn.className = "";
            if (res && res.length > 0) {
                res.forEach(rs => {
                    inertResult(value, 1, rs);
                })
            } else {
                document.println(`未查询到结果`)
            }

        }).catch(e => {
            btn.disabled = false;
            btn.className = "";
            document.println(`未查询到结果,${e.toString()}`)
        })
}

const imgpackButtonInit = () => {
    const ipkPathInput = document.querySelector("#ipkPath")

    let chooseBtn = document.querySelector("#choose_btn");
    chooseBtn.addEventListener("click", () => {
        chooseBtn.disabled = true

        //title, properties, filters
        electron.openFileDialog("选择文件夹", ["openDirectory"], null).then(result => {
            console.log("result", result)
            chooseBtn.disabled = false

            //是否需取消
            if (result.canceled) {
                return;
            }

            //选择内容
            if (result.filePaths.length >= 1) {
                let dir = result.filePaths[0];
                let input = document.querySelector("#ipkPath")

                if (input.value == dir) {
                    return;
                }

                input.value = dir;
                clearResult();
                document.println("选择了新的imagePacks2文件夹,请重新建立缓存")
            }
        })
    });

    let cacheBtn = document.querySelector("#cache_btn");
    cacheBtn.addEventListener("click", () => {
        if (ipkPathInput.value != "") {
            sendChannelBuildCache();
        }
    });

    let testBtn = document.querySelector("#test_btn");
    testBtn.addEventListener("click", () => {
        sql.npkIndex.queryTest().then(result => {
            if (!result) {
                document.println("当前没有ImagePacks2缓存!")
                return;
            }

            document.println("检测到ImagePacks2缓存:")
            document.println(`ImagePacks2路径:${result.path}`)
            document.println(`缓存记录数量:${result.count}`)
        }).catch(err => {
            document.println(err.toString());
        })
    });
}

const searchAllInit = () => {
    let btn = document.querySelector("#all_btn")
    btn.addEventListener("click", () => {
        clearResult();

        sql.npkIndex.queryCountImgLike("")
            .then(data => {
                console.log("data", data);
                if (data && data.num > 0) {
                    page.reset();
                    page.value = "";
                    page.callback = searchImgQuery;
                    page.setCount(data.num);
                    page.query();
                } else {
                    document.println(`未查询到结果`)
                    btn.disabled = false;
                    btn.className = "";
                }
            })
    })
}

const tableExplorer = (element) => {
    let tr = element.parentNode.parentNode;
    let dataid = tr.getAttribute("data-id") //数据库中的id

    sql.npkIndex.queryById(dataid).then(data => {
        if (data) {
            electron.openExplorer(data.path);
        }
    })
}

//动态绑定enter键
const searchImgInputChange = (element) => {
    document.onkeydown = (e) => {
        let theEvent = window.event || e;
        let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
        if (code == 13) {
            document.querySelector("#img-search-btn").click()
            document.onkeydown = null;
        }
    }
}

//动态绑定enter键
const searchNpkInputChange = (element) => {
    document.onkeydown = (e) => {
        let theEvent = window.event || e;
        let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
        if (code == 13) {
            document.querySelector("#npk-search-btn").click()
            document.onkeydown = null;
        }
    }
}

//按下预览按钮
const tableView = (element) => {
    console.log("tableView", element)
    let tr = element.parentNode.parentNode;
    let dataid = tr.getAttribute("data-id") //数据库中的id


    //如果tr有元素id 则显示隐藏内容
    if (tr.id) {
        let token = tr.id.replaceAll("-row", "");
        let pre = document.querySelector("#" + token);
        if (pre) {
            if (pre.className.indexOf("hidden") != -1) {
                pre.className = pre.className.replace("hidden", "").trim();
            } else {
                pre.className += " hidden";
            }

            return;
        }
    }

    //未找到pre
    //查询&&解析
    element.disabled = true;
    element.className += " wait";
    sql.npkIndex.queryById(dataid).then(data => {
        if (data) {
            let token = GetUUID();
            electron.npkSend("getNpkImgAll", token, data.path, data.img);

            //赋予tr一个id
            tr.id = token + "-row";

            //插入pre-tr
            let previewTr = $(`
                <tr class="preview" ref="${dataid}" id="${token}" >
                    <td colspan="2"></td>
                </tr>`);
            $(tr).after(previewTr)
        }
    })
}


const replyToken = (event, channel, token, data) => {
    console.log("replyToken 接收一条回复", event, channel, token, data)

    if (channel == "getNpkImgAll") {
        tableViewToken(token, data);
        return;
    }

    if (channel == "exportNpkAll") {
        // tableViewToken(token, err, data);
        return;
    }

    if (channel == "exportNpkImgAll") {
        // tableViewToken(token, err, data);
        return;
    }

    if (channel == "cache_dirPath") {
        if (data.code == 0) {
            //任务完成或失败
            const ipkPathInput = document.querySelector("#ipkPath")
            ipkPathInput.disabled = false;

            const cache_btn = document.querySelector("#cache_btn")
            cache_btn.disabled = false;
            cache_btn.className = "";

            const choose_btn = document.querySelector("#choose_btn")
            choose_btn.disabled = false;

            const all_btn = document.querySelector("#all_btn")
            all_btn.disabled = false;

            const npkSearchBtn = document.querySelector("#npk-search-btn")
            npkSearchBtn.disabled = false;

            const imgSearchBtn = document.querySelector("#img-search-btn");
            imgSearchBtn.disabled = false;

            document.println(data.text)
            return
        }

        if (data.code == 1) {
            //中间消息
            document.println(data.text)
        }
    }
}


//记录下每个预览有多少png
const tokenCounts = {};

//接受npk服务返回数据
//第一条是data.count指定数据数量
//然后依次按index传送base64  {index:number,base64:number}
const tableViewToken = (token, data) => {
    console.log("tableViewToken 接收一条回复", token, data)

    if (data.code == 0) {  //停止任务
        let row = document.querySelector("#" + token + "-row");
        if (!row) {
            return;
        }

        let button = row.querySelector(".wait");
        button.disabled = false;
        button.className = button.className.replace("wait", "").trim();

        document.println(data.text);
    }


    if (data.code == 1) { //解析一个png成功
        let pre = document.querySelector("#" + token);
        if (!pre) {
            return;
        }

        let td = pre.querySelector("td");

        let div = $(`<div class="preview-div">
                    <label>${data.index}</label>
                    <img src="${data.base64}" onload="previewOnload(this)"></img>
                </div>`
        )
        $(td).append(div);
        tokenCounts[token].current++;
    }

    if (data.code == 2) {  //解析一个png失败
        document.println(`预览失败,${data.text}`);
        if (tokenCounts[token]) {
            tokenCounts[token].current++;
        }
    }

    if (data.code == 3) { //指定png数量
        // let pre = document.querySelector("#"+token);
        // pre.setAttribute("count",data.count)
        tokenCounts[token] = {
            count: data.count, //数据总量
            current: 0,        //已处理数量
        };
        return
    }

    //判断是否已经传输完成
    if (tokenCounts[token].current == tokenCounts[token].count) {
        let row = document.querySelector("#" + token + "-row");
        if (!row) {
            return;
        }
        let button = row.querySelector(".wait");
        button.disabled = false;
        button.className = button.className.replace("wait", "").trim();
    }
}

const exportNpk = (e) => {

}

const exportNpkToken = (token, data) => {

}


const exportImg = (e) => {

}

const exportImgToken = (token, data) => {

}


const selectBgColor = (e) => {
    console.log("selectBgColor", e.value)

    let bgColorText = document.querySelector("#bgColorText")
    let bgColorSpan = bgColorText.querySelector(".innerText")
    let div = bgColorText.querySelector(".innerColor")
    let color;

    switch (e.value) {
        case "0":
            div.style.background = "url('./gw.jpg')";
            color = 'inherit';
            bgColorSpan.style.color = "black";
            break;
        case "1":
            div.style.background = color = "black"
            bgColorSpan.style.color = "white";
            break;
        case "2":
            div.style.background = color = "gray"
            bgColorSpan.style.color = "black";
            break;
        case "3":
            div.style.background = color = "white"
            bgColorSpan.style.color = "black";
            break;
        case "4":
            div.style.background = color = "red"
            bgColorSpan.style.color = "white";
            break;
        case "5":
            div.style.background = color = "blue"
            bgColorSpan.style.color = "white";
            break;
        case "6":
            div.style.background = color = "green"
            bgColorSpan.style.color = "white";
            break;
        case "7":
            div.style.background = color = "yellow"
            bgColorSpan.style.color = "black";
            break;
        case "8":
            div.style.background = color = "purple"
            bgColorSpan.style.color = "white";
            break;
        case "9":
            div.style.background = color = "aqua"
            bgColorSpan.style.color = "black";
            break;
    }

    //遍历已经存在的img
    new Array().slice.call(document.querySelectorAll(".preview-div img"))
        .filter(e => e.nodeType == 1)
        .forEach(e => {
            e.style.background = color;
        })
}

//初始化拖拽文件夹事件
const dragInit = () => {
    const input = document.querySelector("#ipkPath")

    input.addEventListener("drop", (e) => {
        e.preventDefault()
        const files = e.dataTransfer.files;
        if (files && files.length > 0) {
            const path = files[0].path;//获取文件路径
            input.value = path;
            clearResult();
            document.println("选择了新的imagePacks2文件夹,请重新建立缓存")
        }
    })

    //阻止拖拽结束事件默认行为
    input.addEventListener("dragover", (e) => {
        e.preventDefault();
    })
}

window.onload = () => {
    //全局字体颜色
    {
        const topBody = window.top.document.querySelector("body")
        const body = document.querySelector("body")

        if (topBody.style.color) {
            body.style.color = topBody.style.color
        }
    }

    init();
    imgpackButtonInit();
    searchNpkInit();
    searchImgInit();
    searchAllInit();
    dragInit();
}
